function protectH5() {
  // 检测是否为移动端设备
  const isMobile =
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );

  if (isMobile) {
    // 移动端防护策略
    protectMobile();
  } else {
    // 桌面端防护策略
    protectDesktop();
  }
}

// 移动端防护
function protectMobile() {
  // 禁用右键菜单（移动端通常没有右键，但可能有长按菜单）
  document.addEventListener(
    "contextmenu",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 禁用长按选择文本
  document.addEventListener(
    "touchstart",
    (e) => {
      if (e.touches.length > 1) {
        e.preventDefault();
        e.stopPropagation();
      }
    },
    { passive: false }
  );

  // 禁用双指缩放
  document.addEventListener(
    "touchmove",
    (e) => {
      if (e.touches.length > 1) {
        e.preventDefault();
        e.stopPropagation();
      }
    },
    { passive: false }
  );

  // 禁用长按保存图片
  document.addEventListener(
    "touchend",
    (e) => {
      const now = Date.now();
      const lastTouch = (e.target as any).lastTouch || 0;
      if (now - lastTouch < 500) {
        e.preventDefault();
        e.stopPropagation();
      }
      (e.target as any).lastTouch = now;
    },
    true
  );

  // 禁用选择文本
  document.addEventListener(
    "selectstart",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 禁用拖拽
  document.addEventListener(
    "dragstart",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 移动端开发者工具检测（主要针对调试模式）
  detectMobileDevTools();
}

// 桌面端防护
function protectDesktop() {
  // 禁用右键菜单
  document.addEventListener(
    "contextmenu",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 禁用选择文本
  document.addEventListener(
    "selectstart",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 禁用拖拽
  document.addEventListener(
    "dragstart",
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    true
  );

  // 禁用F12等快捷键
  document.addEventListener(
    "keydown",
    (e) => {
      // 阻止常见的开发者工具快捷键
      const forbiddenCombinations = [
        // F12, F5, F10, F11
        () => e.keyCode >= 112 && e.keyCode <= 123,
        // Ctrl+Shift+I
        () => e.ctrlKey && e.shiftKey && e.keyCode === 73,
        // Ctrl+Shift+J
        () => e.ctrlKey && e.shiftKey && e.keyCode === 74,
        // Ctrl+U
        () => e.ctrlKey && e.keyCode === 85,
        // Ctrl+Shift+C
        () => e.ctrlKey && e.shiftKey && e.keyCode === 67,
        // Ctrl+Shift+K (Firefox)
        () => e.ctrlKey && e.shiftKey && e.keyCode === 75,
        // Ctrl+Shift+M (移动端视图切换)
        () => e.ctrlKey && e.shiftKey && e.keyCode === 77,
        // Ctrl+Shift+P (命令面板)
        () => e.ctrlKey && e.shiftKey && e.keyCode === 80,
        // Ctrl+Shift+U (查看源代码)
        () => e.ctrlKey && e.shiftKey && e.keyCode === 85,
        // Ctrl+S (保存页面)
        () => e.ctrlKey && e.keyCode === 83,
        // Ctrl+P (打印页面)
        () => e.ctrlKey && e.keyCode === 80,
      ];

      const isForbidden = forbiddenCombinations.some((fn) => fn());

      if (isForbidden) {
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
    },
    true
  );

  // 多维度开发者工具检测
  let devtoolsOpened = false;
  let detectionCount = 0;
  let lastCheckTime = Date.now();
  let lastWidth = window.innerWidth;
  let lastHeight = window.innerHeight;
  let lastOuterWidth = window.outerWidth;
  let lastOuterHeight = window.outerHeight;

  // 检测页面是否可见（避免最小化时误判）
  let pageVisible = true;

  document.addEventListener("visibilitychange", () => {
    pageVisible = !document.hidden;
    if (pageVisible) {
      // 页面重新可见时重置检测
      detectionCount = 0;
    }
  });

  function detectDevTools() {
    // 如果页面不可见（最小化或切换标签页），跳过检测
    if (!pageVisible) {
      return;
    }

    // 方法1: 窗口尺寸检测（排除最小化情况）
    const heightDiff = Math.abs(window.outerHeight - window.innerHeight);
    const widthDiff = Math.abs(window.outerWidth - window.innerWidth);

    // 检查窗口尺寸是否发生突变（可能是开发者工具打开/关闭）
    const currentWidth = window.innerWidth;
    const currentHeight = window.innerHeight;
    const currentOuterWidth = window.outerWidth;
    const currentOuterHeight = window.outerHeight;

    const innerSizeChanged =
      Math.abs(currentWidth - lastWidth) > 50 ||
      Math.abs(currentHeight - lastHeight) > 50;

    const outerSizeChanged =
      Math.abs(currentOuterWidth - lastOuterWidth) > 50 ||
      Math.abs(currentOuterHeight - lastOuterHeight) > 50;

    lastWidth = currentWidth;
    lastHeight = currentHeight;
    lastOuterWidth = currentOuterWidth;
    lastOuterHeight = currentOuterHeight;

    // 方法2: Console检测
    let consoleOpened = false;
    try {
      consoleOpened =
        !!window.console &&
        typeof window.console.clear === "function" &&
        window.console.toString().includes("Console");
    } catch (e) {
      // 忽略错误
    }

    // 新增方法：检测控制台是否被调用
    let consoleUsed = false;
    try {
      // 通过检查console方法是否被重写来判断是否被使用
      consoleUsed = console.log !== console.log;
    } catch (e) {
      // 忽略错误
    }

    // 新增方法：检测开发者工具特有属性
    let devtoolsProps = false;
    try {
      // 检测开发者工具特有的属性
      devtoolsProps =
        !!window.Firebug ||
        (window.console && typeof window.console.firebug !== "undefined");
    } catch (e) {
      // 忽略错误
    }

    // 改进的综合判断逻辑
    const isDevToolsOpen =
      // 高度/宽度差异检测（不依赖尺寸变化）
      heightDiff > 150 ||
      widthDiff > 150 ||
      // 尺寸变化检测（开发者工具打开/关闭时的突变）
      innerSizeChanged ||
      outerSizeChanged ||
      // 控制台被使用
      consoleUsed ||
      // 开发者工具特有属性
      devtoolsProps ||
      // 极端尺寸检测（非常小的窗口）
      window.innerWidth < 50 ||
      window.innerHeight < 50;

    // 只有连续多次检测到才触发防护
    if (isDevToolsOpen) {
      detectionCount++;
      if (detectionCount >= 2 && !devtoolsOpened) {
        // 连续2次检测到才确认
        devtoolsOpened = true;
        handleDevToolsDetection();
      }
    } else {
      detectionCount = 0; // 重置计数器
      devtoolsOpened = false;
    }
  }

  // 定期检测
  setInterval(detectDevTools, 1000); // 检测间隔

  // 页面加载后立即检测一次
  setTimeout(detectDevTools, 3000); // 延迟检测，避免页面加载时的误判
}

// 移动端开发者工具检测
function detectMobileDevTools() {
  let checkCount = 0;
  let isDebugging = false;
  let consecutiveDetections = 0; // 连续检测计数

  // 通过性能检测判断是否在调试
  function checkPerformance() {
    if (window.performance && window.performance.timing) {
      const timing = window.performance.timing;
      const loadTime = timing.loadEventEnd - timing.navigationStart;

      // 如果页面加载时间异常长，可能在调试 (提高阈值)
      if (loadTime > 60000 && checkCount > 10) {
        // 60秒且检测10次以上
        return true;
      }
    }
    return false;
  }

  // 检测控制台对象
  function checkConsole() {
    try {
      // 更严格的检测条件
      return (
        typeof console !== "undefined" &&
        typeof console.log === "function" &&
        console.clear &&
        console.log.toString().includes("[native code]") === false
      );
    } catch (e) {
      return false;
    }
  }

  // 定期检测
  setInterval(() => {
    checkCount++;

    // 检测调试相关特征
    const hasConsole = checkConsole();
    const performanceIssue = checkPerformance();

    // 只有同时满足多个条件才认为是调试模式
    if ((hasConsole || performanceIssue) && checkCount > 5) {
      consecutiveDetections++;
      if (consecutiveDetections >= 2 && !isDebugging) {
        // 连续2次检测到
        isDebugging = true;
        handleMobileDevToolsDetection();
      }
    } else {
      consecutiveDetections = 0; // 重置计数
    }
  }, 2000); // 延长检测间隔
}

// 处理桌面端检测到开发者工具的情况
function handleDevToolsDetection() {
  // 方法1: 弹出警告
  alert("请关闭开发者工具以获得最佳体验");

  // 方法2: 显示遮罩层
  showDevToolsWarning();
}

// 处理移动端检测到调试的情况
function handleMobileDevToolsDetection() {
  // 移动端处理方式
  showMobileWarning();
}

// 显示桌面端开发者工具警告遮罩
function showDevToolsWarning() {
  // 移除已存在的遮罩
  const existingOverlay = document.getElementById("devtools-overlay");
  if (existingOverlay) {
    existingOverlay.remove();
  }

  // 创建遮罩层
  const overlay = document.createElement("div");
  overlay.id = "devtools-overlay";
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.9);
    z-index: 999999;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 20px;
    text-align: center;
    backdrop-filter: blur(10px);
  `;

  overlay.innerHTML = `
    <div style="padding: 20px; max-width: 90%;">
      <h2 style="margin-bottom: 20px; color: #ff4d4f;">检测到开发者工具</h2>
      <p style="margin-bottom: 10px;">为了您的最佳体验，请关闭开发者工具</p>
      <p style="font-size: 16px; margin-bottom: 30px; color: #ccc;">
        Developer tools detected. Please close developer tools for optimal experience.
      </p>
      <button onclick="location.reload()" style="
        padding: 12px 24px;
        background: #007aff;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 16px;
        transition: background 0.3s;
      " onmouseover="this.style.background='#0056b3'" onmouseout="this.style.background='#007aff'">
        刷新页面 Refresh Page
      </button>
    </div>
  `;

  document.body.appendChild(overlay);
}

// 显示移动端警告
function showMobileWarning() {
  // 移除已存在的遮罩
  const existingOverlay = document.getElementById("mobile-warning-overlay");
  if (existingOverlay) {
    existingOverlay.remove();
  }

  // 创建遮罩层
  const overlay = document.createElement("div");
  overlay.id = "mobile-warning-overlay";
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.95);
    z-index: 999999;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 18px;
    text-align: center;
    backdrop-filter: blur(5px);
    padding: 20px;
    box-sizing: border-box;
  `;

  overlay.innerHTML = `
    <div style="padding: 20px; max-width: 95%;">
      <h2 style="margin-bottom: 20px; color: #ff9500;">调试模式检测</h2>
      <p style="margin-bottom: 15px;">检测到您可能在调试模式下运行应用</p>
      <p style="font-size: 14px; margin-bottom: 25px; color: #ccc; line-height: 1.5;">
        Debug mode detected. For security and performance reasons, 
        please exit debug mode and restart the application.
      </p>
      <div style="display: flex; gap: 15px; flex-wrap: wrap; justify-content: center;">
        <button onclick="location.reload()" style="
          padding: 12px 20px;
          background: #007aff;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          font-size: 14px;
          transition: background 0.3s;
        " onmouseover="this.style.background='#0056b3'" onmouseout="this.style.background='#007aff'">
          重新加载 Reload
        </button>
        <button onclick="this.parentElement.parentElement.parentElement.remove()" style="
          padding: 12px 20px;
          background: transparent;
          color: #ccc;
          border: 1px solid #666;
          border-radius: 6px;
          cursor: pointer;
          font-size: 14px;
          transition: all 0.3s;
        " onmouseover="this.style.background='rgba(255,255,255,0.1)';this.style.color='white'" 
           onmouseout="this.style.background='transparent';this.style.color='#ccc'">
          继续使用 Continue
        </button>
      </div>
    </div>
  `;

  document.body.appendChild(overlay);
}

export default protectH5;
